package app

import (
	"net/url"
	"strings"
	"time"

	. "gitee.com/tomatomeatman/golang-repository/bricks/model"
	uUrl "gitee.com/tomatomeatman/golang-repository/bricks/utils/function/url"
	. "gitee.com/tomatomeatman/golang-repository/bricks/utils/gin"
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
)

type Cloud struct{}

/**
 * 初始化
 */
func init() {
	if !(AppUtil{}.HasSection("CloudCenter")) {
		return
	}

	go GinUtil{}.RegisterController("/cloud/monitor", POST, Cloud{}.CloudMonitor)
	go GinUtil{}.RegisterController("/cloud/monitor", GET, Cloud{}.CloudMonitor)
}

/**
 * 注册服务到注册中心
 */
func (Cloud) RegistraCloud() {
	if !(AppUtil{}.HasSection("CloudCenter")) {
		return
	}

	cloudCenterSite := AppUtil{}.ReadConfigKey("CloudCenter", "Site", "").(string)
	cloudCenterUser := AppUtil{}.ReadConfigKey("CloudCenter", "User", "").(string)
	cloudCenterPassword := AppUtil{}.ReadConfigKey("CloudCenter", "Password", "").(string)
	DomainName := AppUtil{}.ReadConfigKey("System", "DomainName", "").(string)
	DomainPort := AppUtil{}.ReadConfigKey("System", "DomainPort", "").(string)

	Port := AppUtil{}.ReadConfigKey("System", "Port", "8080").(string)
	Name := AppUtil{}.ReadConfigKey("System", "Name", "").(string)

	var json strings.Builder
	json.WriteString("{\"sSign\":\"")
	json.WriteString(Name)
	json.WriteString("Server\",\"serverPort\":\"")
	json.WriteString(Port)
	json.WriteString("\",\"serverIp\":\"unknown\",\"domainName\":\"")
	json.WriteString(DomainName)
	json.WriteString("\",\"domainPort\":\"")
	json.WriteString(DomainPort)
	json.WriteString("\"}")

	var host strings.Builder
	host.WriteString("http://")
	host.WriteString(cloudCenterSite)
	host.WriteString("/add")

	params := map[string]interface{}{
		"user":         cloudCenterUser,
		"key":          cloudCenterPassword,
		"sSign":        Name + "Server",
		"sRegisterTxt": url.QueryEscape(json.String()),
	}

	urlStr := strings.Replace(host.String(), "http://http://", "http://", 1)

	for {
		me := uUrl.HttpUtil{}.DoGet(urlStr, params, nil)
		if me.Gsuccess {
			//fmt.Println("注册服务成功")
			seelog.Info("注册服务成功")
			return
		}

		seelog.Error("注册服务失败,返回内容:", me)
		time.Sleep(time.Second * 5) //休眠5秒
	}
}

// #region @Api {title=取服务器外网IP}
// @return {type=json explainType=MsgEmity<string> explain=返回IP}
// @RequestMapping {name=ServerIp type=GET value=/ipcity/ip/server}
// #endregion
func (Cloud) CloudMonitor(ctx *gin.Context) interface{} {
	return MsgEmity{}.Success(time.Now().Format("2006-01-02 15:04:05"), "访问成功")
}
